<template>
  <div v-loading="loading">
    <div class="scroll-text" v-if="!hide">
      <img class="mings" src="../../../assets/image/info.png" />
      <marquee
        ><b>Eletile</b> Business Process for You ; {{$t('webAuto.huanyinshiyong')}}
        <strong>IBPM</strong> {{$t('webAuto.gongzuoliu')}} <i>({{$t('webAuto.gongzuoliu')}})</i></marquee
      >
    </div>
    <div class="fixed-search hidden-xs-only" v-if="!hide">
      <el-input
        clearable
        :placeholder="$t('webAuto.sousuoFrom')"
        prefix-icon="search"
        v-model="searchForm"
      ></el-input>
    </div>
    <el-row :gutter="20" v-if="!hide">
      <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="count" @click="to('unfinished')">
          <div>
            <p>{{ $t("calendar.disposal") }}</p>
            <div style="color: #ec8151 !important">{{ taskCount.todo }}</div>
          </div>
          <img src="../../../assets/image/pending.png" />
        </div>
      </el-col>
      <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="count" @click="to('submit')">
          <div>
            <p>{{ $t("calendar.initiated") }}</p>
            <div style="color: #3296fa">{{ taskCount.mySubmited }}</div>
          </div>
          <img src="../../../assets/image/submit.png" />
        </div>
      </el-col>
      <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="count" @click="to('finished')">
          <div>
            <p>{{ $t("calendar.processed") }}</p>
            <div style="color: green">{{ taskCount.finished }}</div>
          </div>
          <img src="../../../assets/image/finished.png" />
        </div>
      </el-col>
      <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
        <div class="count" @click="to('cc')">
          <div>
            <p>{{ $t("calendar.aboutMe") }}</p>
            <div style="color: #565cff">{{ taskCount.cc }}</div>
          </div>
          <img src="../../../assets/image/cc.png" />
        </div>
      </el-col>
    </el-row>
    <div class="group" v-if="searchForm && searchForm.trim() !== ''">
      <div class="group-title">{{$t('webAuto.sousuoReslut')}}</div>
      <div class="group-container">
        <div
          class="group-item"
          v-for="(item, index) in searchResult"
          :key="index"
          @click="enterItem(item)"
        >
          <div>
            <iconify
              class="icon"
              :icon="item.logo.icon"
              :style="{ '--bgc': item.logo.background }"
            />
            <ellipsis class="item-name" hover-tip :content="item.formName" />
          </div>
        </div>
        <el-empty
          v-if="searchResult.length === 0"
          :image-size="100"
          :description="`${$t('webAuto.notserch')} '${searchForm}' ${$t('webAuto.aboutFrom')}`"
        ></el-empty>
      </div>
    </div>
    <div v-else>
      <!-- <div class="group" v-if="recentlyUsed && recentlyUsed.length > 0">
        <div class="group-title">
          最近使用
          <el-link style="float: right" :underline="false" link icon="delete" @click="clearUsed">{{ $t('webAuto.clear') }}</el-link>
        </div>
        <div class="group-container">
          <div class="group-item" v-for="(item, index) in recentlyUsed" :key="index" @click="enterItem(item)">
            <div>
              <iconify class="icon" :icon="item.logo.icon" :style="{ '--bgc': item.logo.background }" />
              <ellipsis class="item-name" hover-tip :content="item.formName" />
            </div>
          </div>
        </div>
      </div> -->
      <!-- <div class="group" v-for="(group, index) in formList.list" :key="index"
        v-show="group.items.length > 0 && group.id > 0">
        <div class="group-title">{{ group.name }}</div>
        <div class="group-container">
          <div class="group-item" v-for="(item, index) in group.items" :key="index" @click="enterItem(item)">
            <div>
              <iconify class="icon" :icon="item.logo.icon" :style="{ '--bgc': item.logo.background }" />
              <ellipsis class="item-name" hover-tip :content="item.formName" />
            </div>
          </div>
        </div>
      </div> -->
      <!-- 新的模式块 -->
      <div class="app-main">
        <div class="a1-left">
          <div class="left-title">{{$t('webAuto.liuchengFL')}}</div>
          <el-scrollbar height="900" class="scrollbar">
            <div class="wrap-scroll">
              <div class="box-card">
                <div
                  :class="selectBox == 0 ? 'text text2' : 'text'"
                  @click="processClick('常用流程', 0)"
                >
                  <p class="cardName">{{ $t('webAuto.CommonProcesses') }}</p>
                  <p class="cardNumber">{{ recentlyUsed?.length || 0 }}</p>
                </div>
              </div>
              <div class="box-card" style="margin-top: 0px">
                  <template  v-for="(item, index) in treeList"
                             :key="index">
                    <div
                      v-if="item.items?.length > 0"
                      :class="index + 1 == selectBox ? 'text text2' : 'text'"
                      @click="processClick(item, index)"
                    >
                      <p class="cardName" >{{ item.name }}</p>
                      <p class="cardNumber" >{{ item.items?.length || 0 }}</p>
                    </div>
                  </template>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div class="a1-right">
          <div class="headers">
            <p class="main-header">{{$t('webAuto.NewProcesses')}}</p>
            <div class="sort">
              <span style="color: #d64445">（{{ headerName }}） </span>
              <span style=""
                >{{$t('webAuto.incloudProcesses')}}:
                {{
                  headerName == "常用流程" ? recentlyUsed?.length : qty
                }}</span
              >
            </div>
          </div>
          <div class="card">
            <el-empty :image-size="200" v-if="treeList.length <= 0" />
            <div class="cardShow" v-else>
              <el-scrollbar
                max-height="1100px"
                height="740px"
                class="scrollbar"
              >
                <!-- click="enterItem(item)" -->
                <div
                  class="cardBox"
                  v-for="(item, index) in recentlyUsed"
                  :key="index"
                  @click="enterItem2(item)"
                  v-show="headerName == '常用流程'"
                >
                  <div>
                    <iconify
                      class="icon"
                      :icon="item.logo.icon"
                      :style="{ '--bgc': item.logo.background }"
                    />
                    <ellipsis
                      class="item-name"
                      hover-tip
                      :content="item.formName"
                    />
                  </div>
                </div>
                <div
                  class="cardBox"
                  v-for="(item, index) in processList"
                  :key="index"
                  @click="enterItem2(item)"
                  v-show="headerName != '常用流程'"
                >
                  <div>
                    <iconify
                      class="icon"
                      :icon="item.logo.icon"
                      :style="{ '--bgc': item.logo.background }"
                    />
                    <ellipsis
                      class="item-name"
                      hover-tip
                      :content="item.formName"
                    />
                  </div>
                </div>
              </el-scrollbar>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 发起打开流程 -->
    <w-dialog
      v-if="openItemDl"
      :ok-loading="submitLoading"
      :title="`${$t('webAuto.initiate')} - ${selectForm.formName}`"
      closeFree
      v-model="openItemDl"
      :okText="$t('webAuto.Submit')"
      :cancelText="$t('webAuto.cancel')"
      :onFlieText="$t('webAuto.SaveDraft')"
      @cancel="openItemDl = false"
      @ok="submitForm"
      @onFlie="submitForm2"
      :fullscreen="true"
      style="margin: 0px !important"
    >
      <initiate-process
        ref="processForm"
        @render-ok="submitLoading = false"
        :code="selectForm.formId"
        v-if="openItemDl"
        @fail="submitLoading = false"
        @ok="(openItemDl = false), (submitLoading = false)"
        style="width: 98%"
        :draft="formDatas"
      />
    </w-dialog>

    <!-- 存稿弹框 -->
    <el-dialog
      v-if="openItemDl2"
      :close-on-click-modal="false"
      :ok-loading="submitLoading"
      :title="`${$t('homePage.pleaseDraft')} - ${selectForm.formName}`"
      closeFree
      width="40%"
      v-model="openItemDl2"
    >
      <el-table
        :data="tableData"
        stripe
        style="width: 100%; margin: 0 auto"
        highlight-current-row
        @row-dblclick="rowDblClick"
        :header-cell-style="{
          color: '#000',
          borderColor: ' #CCC',
          background: '#f9f9f9',
        }"
      >
        <el-table-column type="index" width="50" label="#" />
        <el-table-column prop="name" :label="$t('webAuto.ManuscriptNumber')" />
        <el-table-column prop="address" :label="$t('webAuto.operate')" width="150">
          <template #default="scope">
            <el-button
              type="text"
              @click="handleClick(scope.row)"
              style="color: red"
              >{{$t('webAuto.delete')}}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="openForm"> {{$t('webAuto.DoDraft')}} </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getGroupModelsByUser,
  getProcessCountData,
  getStaging,
  getFormDataStaging,
  deleteFormDataStaging,
} from "@/api/modelGroup";
import InitiateProcess from "../InitiateProcess.vue";
import store from "../../../store/index";
import { getProcessComunes } from "@/api/home";

export default {
  name: "ApprovalGroup",
  components: { InitiateProcess },
  props: {
    hide: { type: Boolean, default: false },
  },
  data() {
    return {
      taskCount: {
        todo: 0,
        mySubmited: 0,
        finished: 0,
        cc: 0,
      },
      submitLoading: false,
      recentlyUsed: [],
      //searchResult: [],
      searchForm: "",
      loading: false,
      openItemDl: false,
      openItemDl2: false,
      tableData: [], //存稿list的key
      tableList: {}, //存稿的list
      draft: false, //是否存稿
      selectForm: {},
      formDatas: {},
      formItem: {},
      actives: [],
      formList: {
        list: [],
        inputs: "",
        searchResult: [],
      },
      pending: {
        list: [],
      },
      popupStyle: {
        height: "100%",
        width: "100%",
        background: "#f7f7f9",
      },
      selectBox: 0,
      treeList: [],
      processList: [],
      headerName: "常用流程",
      qty: 0,
    };
  },
  created() {
    window.addEventListener("beforeunload", () => {
      this.refresh();
    });
  },
  mounted() {
    this.getGroupModels();
    this.getCountData();
    // 常用流程获取 从本地存储的获取+接口获取
    this.recentlyUsed = JSON.parse(
      localStorage.getItem(`recentlyUsed:${(this.loginUser || {}).id}`) || "[]"
    );
    getProcessComunes().then((res) => {
      // console.log('111112323',res.data)
      if (res.status == 200) {
        Object.keys(res.data).forEach((key) => {
          let arr=this.recentlyUsed.filter(x=>x.formId==key.split("|")[1])
          if(!arr.length){
            this.recentlyUsed.unshift({
              formName: key.split("|")[0],
              formId: key.split("|")[1],
              badge: res.data[key],
              processDefId: key.split("|")[2],
              logo: {
                background: "#1e90ff",
                icon: "bi:people-fill",
              },
          });
          }
        });
      }
    });

    // console.log( this.recentlyUsed )
  },
  computed: {
    isMobile() {
      return window.screen.width < 450;
    },
    loginUser() {
      return this.$store.state.loginUser;
    },
    searchResult() {
      let result = [];
      this.formList.list.forEach((group) => {
        group.items.forEach((item) => {
          if (item.formName.indexOf(this.searchForm) > -1) {
            result.push(item);
          }
        });
      });
      return result;
    },
  },
  methods: {
    refresh() {
      window.location.reload();
    },
    getGroupModels() {
      this.loading = true;
      const idSet = new Set();
      getGroupModelsByUser()
        .then((rsp) => {
          this.treeList = [];
          this.loading = false;
          this.formList.list = rsp.data;
          this.formList.list.forEach((group) => {
            this.actives.push(group.name);
            group.items.forEach((item) => {
              item.logo = JSON.parse(item.logo);
              idSet.add(item.formId);
            });
          });
          this.groups = rsp.data;
          this.filterRecentlyUsed(idSet);

          // 新首页使用
          let flowArr = [];
          rsp.data.forEach((item) => {
            if (item.name == "其他" || item.name == "已停用") {
              return
            }
            item.items.forEach((a) => {
                flowArr.push(a);
              });
            this.treeList.push(item);
          });
          this.treeList.push({ id: 9999, name: "所有流程", items: flowArr });
          // console.log(this.treeList)
        })
        .catch((err) => {
          this.loading = false;
          this.$err(err, this.$t('webAuto.huoquFZError'));
          this.recentlyUsed.length = 0;
          this.$router.push("/login");
        });
    },
    async filterRecentlyUsed(collect) {
      this.recentlyUsed = this.recentlyUsed.filter((v) =>
        collect.has(v.formId)
      );
    },
    getCountData() {
      getProcessCountData().then((rsp) => {
        this.taskCount = rsp.data;
      });
    },
    to(path) {
      this.$router.push("/workspace/" + path);
    },
    // 发起流程打开的画面
    enterItem(item) {
      if (!this.$isNotEmpty(item.processDefId)) {
        this.$message.warning(this.$t('webAuto.ProcessesNotInset'));
        return;
      }
      this.selectForm = item;
      this.openItemDl = true;
      this.recentlyUsed.removeByKey("formId", item.formId);
      this.recentlyUsed.push(item);
      if (this.recentlyUsed.length >= 20) {
        this.recentlyUsed.splice(1, this.recentlyUsed.length - 1);
      }
      localStorage.setItem(
        `recentlyUsed:${(this.loginUser || {}).id}`,
        JSON.stringify(this.recentlyUsed)
      );
      if (this.isMobile) {
        this.$router.push("/mbinitiate?code=" + item.formId);
      }
    },
    // 存稿弹框操作
    enterItem2(item) {
      this.openItemDl2 = true;
      this.selectForm = item;
      this.tableData = [];
      // console.log(this.selectForm)
      getFormDataStaging(item.formId)
        .then((res) => {
          Object.keys(res.data).forEach((item) => {
            this.tableData.push({
              name: item,
            });
          });
          this.tableList = res.data;
          if (!this.tableData.length) {
            this.openItemDl2 = false;
            this.enterItem(this.selectForm);
          }
        })
        .catch((err) => {
          this.$err(err, this.$t('webAuto.cungaoShibai'));
        });
    },
    clearUsed() {
      this.recentlyUsed = [];
      localStorage.setItem(`recentlyUsed:${(this.loginUser || {}).id}`, "[]");
    },
    submitForm() {
      this.$refs.processForm.validate((validForm, validProcess) => {
        console.log(this.$refs.processForm);
        if (!this.isMobile) {
          if (validForm && validProcess) {
            localStorage.removeItem("formItem");
            store.commit("formItemClear");
            this.$refs.processForm.submit();
          } else {
            this.$message.warning(this.$t('webAuto.refineOptions'));
          }
        }
      });
    },
    //过滤前端undefined的值
    cleanUndefined(obj) {
      if (typeof obj === "object" && obj !== null) {
        if (Array.isArray(obj)) {
          return obj.map((item) => this.cleanUndefined(item));
        } else {
          const cleaned = {};
          for (const key in obj) {
            const value = obj[key];
            cleaned[key] =
              value === undefined ? "" : this.cleanUndefined(value);
          }
          return cleaned;
        }
      } else {
        return obj === undefined ? "" : obj;
      }
    },
    // 保存存稿
    submitForm2() {
      this.$refs.processForm.validate((validForm, validProcess) => {
        // console.log('表单谢谢', this.$refs.processForm)
        //  存稿的相关逻辑
        if (!this.$refs.processForm.formData.stagingDate) {
          this.$refs.processForm.formData.stagingDate = null;
        }
        console.log("formId", this.selectForm.formId);
        getStaging({
          formId: this.selectForm.formId,
          param: this.cleanUndefined(this.$refs.processForm.formData),
        }).then((res) => {
          // console.log(res)
          this.$message.warning(this.$t('webAuto.ProcessDraft') + res.data);
        });
      });
    },
    // 分类点击查询
    processClick(item, index) {
      // console.log(item)
      this.headerName = item == this.$t('webAuto.CommonProcesses') ? this.$t('webAuto.CommonProcesses') : item.name;
      this.qty = item.items?.length || 0;
      this.selectBox = index + 1;
      this.getGroupModels();
      this.processList = item.items;
    },
    //不使用存稿的状态
    openForm() {
      this.openItemDl2 = false;
      this.formDatas = {};
      this.enterItem(this.selectForm);
    },
    // 删除存稿
    handleClick(item) {
      deleteFormDataStaging({
        stagingDate: item.name,
        formId: this.selectForm.formId,
      })
        .then((res) => {
          this.$message.warning(res.data);
          let subscript = "";
          this.tableData.filter(function (value, index, arr) {
            if (value.name == item.name) {
              subscript = index;
            }
          });
          this.tableData.splice(subscript, 1);
        })
        .catch((err) => {
          this.$message.warning(this.$t('webAuto.DeleteFailed') + err.data);
        });
    },
    // 使用存稿打开的方法
    rowDblClick(row) {
      this.draft = true;
      this.formDatas = this.tableList[row.name];
      this.openItemDl = true;
      this.openItemDl2 = false;
    },
  },
};
</script>

<style lang="less" scoped>
.group {
  border-radius: 15px;
  padding: 20px 20px;
  margin: 0 15px 15px 15px;
  background: @theme-aside-bgc;

  .group-title {
    font-size: 15px;
    color: #303133;
    margin-bottom: 5px;
  }

  .group-container {
    display: flex;
    flex-wrap: wrap;
  }

  .group-item {
    display: inline-block;
    cursor: pointer;
    border-radius: 10px;
    text-align: center;
    margin: 5px;
    padding: 10px;
    width: 70px;

    .icon {
      padding: 8px;
      border-radius: 8px;
      font-size: 20px;
      color: #fff;
      background: var(--bgc);
      height: 20px;
      width: 20px;
      line-height: 20px;

      &:hover {
        box-shadow: 0 0 15px 0 #9f9999;
        //padding: 10px;
      }
    }

    .item-name {
      font-size: 12px;
      color: #303133;
      max-width: 80px;
      margin-top: 3px;
    }

    & > div {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
}

.fixed-search {
  position: fixed;
  top: 15px;
  right: 220px;
}

.count {
  cursor: pointer;
  position: relative;
  background: @theme-aside-bgc;
  border-radius: 8px;
  height: 80px;
  margin: 0 15px 20px 15px;

  & > div {
    left: 15px;
    position: absolute;

    div {
      color: #b9b8b8;
      font-size: 22px;
      font-weight: bold;
    }
  }

  p {
    color: #303133;
    font-weight: 600;
    font-size: 14px;
  }

  img {
    position: absolute;
    right: 15px;
    top: 20px;
    width: 40px;
    height: 40px;
  }

  &:hover {
    box-shadow: 0 0 10px #eeeeee;
  }
}

// 新的模块
.app-main {
  height: auto;
  width: 100%;
  padding: 0;
  overflow-y: auto;
  display: flex;
  margin: 0 15px 15px 15px;

  .a1-left {
    width: 200px;
    min-width: 200px;
    height: 100%;
    background: #f1f1f1;
    color: #333;
    position: relative;

    .left-title {
      font-size: 20px;
      line-height: 65px;
      padding-left: 15px;
    }

    .wrap-scroll {
      height: calc(100vh - 70px);
      box-sizing: border-box;
      font-family: Avenir, Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      font-size: 14px;
      position: relative;
      overflow-x: hidden;
      overflow-y: auto;
      padding-bottom: 70px;
    }
  }
}

.box-card {
  flex: 1;
  overflow: hidden;
  position: relative;
  -webkit-transition: opacity 0.3s;
  transition: opacity 0.3s;
  width: 100%;
  background: none;
  box-sizing: border-box;
  margin-top: 15px;

  .text {
    margin: 0;
    padding: 0 0 0 10px;
    white-space: nowrap;
    list-style: none;
    outline: 0;
    color: rgba(0, 0, 0, 0.65);
    font-size: 14px;
    font-variant: tabular-nums;
    height: 40px;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;

    .cardName {
      text-align: left;
      flex: 1;
    }

    .cardNumber {
      height: 100%;
      width: 30px;
      text-align: center;
    }
  }

  .text2 {
    background-color: #fff;
  }

  .text:hover {
    background-color: #e8f7ff;
  }
}

.a1-right {
  flex: 1;
  width: calc(100vw - 325px);
  background: #fff;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;

  .headers {
    padding: 0 20px;
    border-bottom: 1px solid #ddd;
    box-sizing: border-box;

    .main-header {
      color: #333;
      font-size: 20px;
      line-height: 20px;
      margin: 0 !important;
      position: relative;
      padding-left: 20px;
      line-height: 70px;
    }

    .main-header::after {
      content: "";
      height: 20px;
      width: 5px;
      background-color: #333;
      position: absolute;
      left: 8px;
      top: 25px;
    }

    .sort {
      height: 50px;
      padding-left: 10px;
      font-size: 15px;
    }
  }

  .card {
    flex: 1;
    box-sizing: border-box;
    overflow: hidden;

    .cardShow {
      height: 100%;
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      align-content: flex-start;
      overflow: auto;
    }
  }
}
.scrollbar {
  width: 100%;
}
.cardBox {
  display: inline-block;
  cursor: pointer;
  border-radius: 10px;
  text-align: center;
  margin: 5px;
  padding: 10px;
  width: 230px;
  height: 55px;

  .icon {
    padding: 8px;
    border-radius: 8px;
    font-size: 20px;
    color: #fff;
    background: var(--bgc);
    height: 20px;
    width: 20px;
    line-height: 20px;
  }

  .item-name {
    font-size: 15px;
    color: #303133;
    width: 230px;
    margin-top: 3px;
  }
}

.scroll-text {
  width: 400px;
  font-size: 17px;
  color: rgb(175, 33, 33);
  white-space: nowrap;
  overflow: hidden;
  box-sizing: border-box;
  animation: scroll 10s linear infinite;
  position: fixed;
  top: 15px;
  left: 95px;
  z-index: 12;
}

.mings {
  width: 25px;
  height: 25px;
}

::v-deep .el-table__body tr.current-row > td {
  color: #fff;
  background: #ebb577 !important;
}
</style>
